package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

@Component
@Slf4j
public class MyTask {
    @Autowired
    private OrderMapper orderMapper;

    //處理超過15分鐘沒有支付的訂單
    @Scheduled(cron = "0 * * * * ?")
    public void handleUnpaidOrder() {
        //現在是7:00,查到6:45以前下單為超時
        LocalDateTime now = LocalDateTime.now();
       LocalDateTime time = now.minusMinutes(15);
        //查詢超時訂單
        List<Orders> orderList = orderMapper.getByStatusAndOrderTime(Orders.PENDING_PAYMENT, time);

        if (orderList != null && orderList.size() > 0) {
            for (Orders order : orderList) {
                log.info("訂單編號：{}，超時未支付，已取消", order.getId());
                order.setStatus(Orders.CANCELLED);
                order.setCancelTime(now);
                order.setCancelReason("訂單超時未支付，已取消");
                orderMapper.update(order);
            }
        }

    }

    //處理派送中的訂單
    @Scheduled(cron = "0 0 1 * * ?")
    public void handleDeliveryOrder() {
        LocalDateTime now = LocalDateTime.now();
       LocalDateTime time = now.minusMinutes(60);
        List<Orders> list = orderMapper.getByStatusAndOrderTime(Orders.DELIVERY_IN_PROGRESS, now);

        if (list!= null && list.size() > 0) {
            log.info("有{}筆派送中的訂單", list.size());
            for (Orders order : list) {
                log.info("處理派送中訂單:{}",order.getId());
                order.setStatus(Orders.COMPLETED);
                order.setDeliveryTime(now);
                orderMapper.update(order);
            }
        }


    }

}
